import random
import ast

from Utility import security_swxlbjs
from urllib import parse, request

JM = security_swxlbjs.Security()


def Authentication(BaseContent, ProgramName, Port, PubKey, PriKey, Url):
    try:
        Key = "".join(random.sample('0123456789qwertyuiopasdfghjklzxcvbnm!@#$%^&*()', int(8 * random.randint(2, 4))))
        SAesS = security_swxlbjs.SAes(Key)
        SRasS = security_swxlbjs.SRsa(pubOutside=PubKey, priOutside=PriKey)
        Content = JM.Encryption(str({"ProgramName": ProgramName, "Port": Port}))
        Content = SAesS.Encryption(Content)
        Content = SRasS.Encryption(Content)
        Content = {"Content": Content}
        Key = {"Key": SRasS.Encryption(JM.Encryption(Key))}
        textmod = dict()
        textmod.update(BaseContent)
        textmod.update(Content)
        textmod.update(Key)
        textmod = parse.urlencode(textmod).encode('utf-8')
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko', }
        req = request.Request(Url, textmod, headers=header_dict)
        req = request.urlopen(req)
        Data = [SAesS.Decryption(SRasS.Decryption(x)) if (x is not None) else None for x in (ast.literal_eval(req.read().decode('utf-8')))]
    except:
        Data = [None, None]
    finally:
        return Data
